import { GraphQLClient } from '@fishx/graphql-client';
import moment from 'moment';
import gql from "gql-tag";
import { v4 as uuid } from 'uuid';
import copy from 'copy-to-clipboard';
import cloneDeep from 'lodash/cloneDeep';
import { defaultSwagger } from './defaultSwagger';
import { fetch } from '@fishx/rest';
import { utils } from 'fishx';
import { Modal } from '@whalecloud/fdx';
import { serverActionList } from './userServerTypes';

let restData = [defaultSwagger];
const { dateUtils } = utils;
const dateReg = /(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)/g;
const timeReg = /([01]?\d|2[0-3]):[0-5]?\d:[0-5]?\d/g;

function getQueryVariable(variable) {
  if (window.location.hash.indexOf('?') !== -1) {
    const query = window.location.hash.split('?')[1];
    const vars = query.split("&");
    for (let i = 0; i < vars.length; i++) {
      const pair = vars[i].split("=");
      if (pair[0] === variable) {
        return pair[1];
      }
    }
  }
  return '';
}

function getCookie(name) {
  const strcookie = document.cookie;
  const arrcookie = strcookie.split("; ");
  for (let i = 0; i < arrcookie.length; i++) {
    const arr = arrcookie[i].split("=");
    if (arr[0] === name) {
      return arr[1];
    }
  }
  return "";
}

const jwtToken = NODE_ENV === 'development' ? `Bearer ` : 'Bearer ' + getCookie('tokenCode');

const headerName = NODE_ENV === 'development' ? 'Web-Ide-Dev' : 'Wdp';

const swaggerList = `[{"swagger":"2.0","info":{"description":"This is Swagger UI environment generated for the Order Catalog Management specification","version":"1.0.0","title":"Order Catalog Management"},"host":"localhost:8080","basePath":"/cocr-service","tags":[{"name":"Offer","description":"Offer Controller"}],"paths":{"/cocr/v1/cpc/catalog":{"get":{"tags":["Offer"],"summary":"Offer catalog Inquiry","description":"Query offer catalog by channel","operationId":"listOfferCatgUsingGET","produces":["*/*"],"parameters":[{"name":"channelId","in":"query","description":"Contact Channel ID","required":true,"type":"integer","format":"int64","allowEmptyValue":false}],"responses":{"200":{"description":"OK","schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"catgClass":{"type":"string","description":"Catalog Class"},"catgCode":{"type":"string","description":"Catalog code"},"catgId":{"type":"integer","format":"int64","description":"Offer catalog ID"},"catgName":{"type":"string","description":"Offer catalog Name"},"catgType":{"type":"string","description":"Catalog Type"},"comments":{"type":"string","description":"Comments"},"extValues":{"type":"object"}},"title":"OfferCatgCO"}},"empty":{"type":"boolean"},"errCode":{"type":"string"},"errMessage":{"type":"string"},"notEmpty":{"type":"boolean"},"success":{"type":"boolean"},"traceId":{"type":"string"}},"title":"MultiResponse«OfferCatgCO»"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":false}},"/cocr/v1/cpc/main-offer/list":{"get":{"tags":["Offer"],"summary":"Offer Inquiry","description":"Query offer by catalog and condition","operationId":"listMainOfferUsingGET","produces":["*/*"],"parameters":[{"name":"catgId","in":"query","description":"Offer catalog ID","required":false,"type":"integer","format":"int64"},{"name":"contactChannelId","in":"query","required":false,"type":"integer","format":"int64"},{"name":"custId","in":"query","required":false,"type":"integer","format":"int64"},{"name":"groupBy","in":"query","required":false,"type":"string"},{"name":"msgId","in":"query","required":false,"type":"string"},{"name":"needTotalCount","in":"query","required":false,"type":"boolean"},{"name":"offset","in":"query","required":false,"type":"integer","format":"int64"},{"name":"orderBy","in":"query","required":false,"type":"string"},{"name":"orderDirection","in":"query","required":false,"type":"string"},{"name":"pageIndex","in":"query","required":false,"type":"integer","format":"int64"},{"name":"pageSize","in":"query","required":false,"type":"integer","format":"int64"},{"name":"spId","in":"query","required":false,"type":"integer","format":"int64"},{"name":"staffId","in":"query","description":"Operating staff ID","required":false,"type":"integer","format":"int64"}],"responses":{"200":{"description":"OK","schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"comments":{"type":"string","description":"Comments"},"extValues":{"type":"object"},"mrc":{"type":"integer","format":"int64","description":"List Monthly Rental Charge"},"offerCode":{"type":"string","description":"Offer Code"},"offerId":{"type":"integer","format":"int64","description":"Offer ID"},"offerName":{"type":"string","description":"Offer Name"},"offerType":{"type":"string","description":"7: Main Offer"},"offerTypeName":{"type":"string","description":"Main Offer"},"otc":{"type":"integer","format":"int64","description":"List One-time Charge"},"offerAttrList":{"type":"array","items":{"type":"object","properties":{"attrDetail":{"type":"object","properties":{"attrCode":{"type":"string"},"attrId":{"type":"integer","format":"int64"},"attrName":{"type":"string"},"attrType":{"type":"string"},"configureVisiable":{"type":"string"},"csrVisiable":{"type":"string"},"defaultValue":{"type":"string"},"extAttrCode":{"type":"string"},"inputBatch":{"type":"string"},"inputType":{"type":"string"},"nullable":{"type":"string"}},"title":"AttributeDetailCO"},"attrId":{"type":"integer","format":"int64"},"attrValue":{"type":"array","items":{"type":"object","properties":{"attrId":{"type":"integer","format":"int64"},"attrValueId":{"type":"integer","format":"int64"},"parentAttrId":{"type":"integer","format":"int64"},"parentAttrValueId":{"type":"integer","format":"int64"},"value":{"type":"string"},"valueMark":{"type":"string"}},"title":"AttributeValueDetailCO"}},"defaultValue":{"type":"string"},"excludeFlag":{"type":"string"},"mainOfferAttrId":{"type":"integer","format":"int64"},"offerVerId":{"type":"integer","format":"int64"},"prodSpecId":{"type":"integer","format":"int64"}},"title":"MainOfferAttrDetailCO"}}},"title":"OfferCO"}},"empty":{"type":"boolean"},"errCode":{"type":"string"},"errMessage":{"type":"string"},"notEmpty":{"type":"boolean"},"pageIndex":{"type":"integer","format":"int64"},"pageSize":{"type":"integer","format":"int64"},"success":{"type":"boolean"},"totalCount":{"type":"integer","format":"int64"},"totalPages":{"type":"integer","format":"int64"},"traceId":{"type":"string"}},"title":"PageResponse«OfferCO»"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":false}},"/cocr/v1/cpc/main-offer/{offerId}":{"get":{"tags":["Offer"],"summary":"Offer Detail Inquiry","description":"Query offer detail by ID","operationId":"qryMainOfferDetailUsingGET","produces":["*/*"],"parameters":[{"name":"offerId","in":"path","description":"Offer ID","required":true,"type":"integer","format":"int64"}],"responses":{"200":{"description":"OK","schema":{"type":"object","properties":{"data":{"type":"object","properties":{"comments":{"type":"string"},"diyMethod":{"type":"string"},"effDate":{"type":"string","format":"date"},"expDate":{"type":"string","format":"date"},"grade":{"type":"integer","format":"int64"},"isBundleFlag":{"type":"string"},"mainProductId":{"type":"integer","format":"int64"},"offerAttrList":{"type":"array","items":{"type":"object","properties":{"attrDetail":{"type":"object","properties":{"attrCode":{"type":"string"},"attrId":{"type":"integer","format":"int64"},"attrName":{"type":"string"},"attrType":{"type":"string"},"configureVisiable":{"type":"string"},"csrVisiable":{"type":"string"},"defaultValue":{"type":"string"},"extAttrCode":{"type":"string"},"inputBatch":{"type":"string"},"inputType":{"type":"string"},"nullable":{"type":"string"}},"title":"AttributeDetailCO"},"attrId":{"type":"integer","format":"int64"},"attrValue":{"type":"array","items":{"type":"object","properties":{"attrId":{"type":"integer","format":"int64"},"attrValueId":{"type":"integer","format":"int64"},"parentAttrId":{"type":"integer","format":"int64"},"parentAttrValueId":{"type":"integer","format":"int64"},"value":{"type":"string"},"valueMark":{"type":"string"}},"title":"AttributeValueDetailCO"}},"defaultValue":{"type":"string"},"excludeFlag":{"type":"string"},"mainOfferAttrId":{"type":"integer","format":"int64"},"offerVerId":{"type":"integer","format":"int64"},"prodSpecId":{"type":"integer","format":"int64"}},"title":"MainOfferAttrDetailCO"}},"offerCode":{"type":"string"},"offerGroupList":{"type":"array","items":{"type":"object","properties":{"necessary":{"type":"string"},"offerGroup":{"type":"object","properties":{"comments":{"type":"string"},"effDate":{"type":"string","format":"date"},"expDate":{"type":"string","format":"date"},"groupType":{"type":"string"},"lowerLimit":{"type":"integer","format":"int64"},"offerGroupCode":{"type":"string"},"offerGroupId":{"type":"integer","format":"int64"},"offerGroupName":{"type":"string"},"offerGroupType":{"type":"string"},"shareFlag":{"type":"string"},"stateDate":{"type":"string","format":"date"},"upperLimit":{"type":"integer","format":"int64"}},"title":"OfferGroupDetailCO"},"offerGroupMemList":{"type":"array","items":{"type":"object","properties":{"defaultFlag":{"type":"string"},"hideFlag":{"type":"string"},"memOfferCode":{"type":"string"},"memOfferComments":{"type":"string"},"memOfferId":{"type":"integer","format":"int64"},"memOfferName":{"type":"string"},"memOfferType":{"type":"string"},"memRentListPrice":{"type":"integer","format":"int64"},"memSaleListPrice":{"type":"integer","format":"int64"},"offerGroupCode":{"type":"string"},"offerGroupId":{"type":"integer","format":"int64"},"offerGroupMemId":{"type":"integer","format":"int64"},"offerGroupName":{"type":"string"},"rstrType":{"type":"string"},"seq":{"type":"integer","format":"int64"},"timeUnit":{"type":"string"}},"title":"OfferGroupMemDetailCO"}},"seq":{"type":"integer","format":"int64"}},"title":"MainOfferGroupDetailCO"}},"offerId":{"type":"integer","format":"int64"},"offerName":{"type":"string"},"offerRelaList":{"type":"array","items":{"type":"object","properties":{"destOfferCode":{"type":"string"},"destOfferComments":{"type":"string"},"destOfferEffDate":{"type":"string","format":"date"},"destOfferExpDate":{"type":"string","format":"date"},"destOfferId":{"type":"integer","format":"int64"},"destOfferName":{"type":"string"},"destOfferState":{"type":"string"},"destRentListPrice":{"type":"integer","format":"int64"},"destSaleListPrice":{"type":"integer","format":"int64"},"offerRelaAttr":{"type":"array","items":{"type":"object","properties":{"attrCode":{"type":"string"},"attrId":{"type":"integer","format":"int64"},"attrName":{"type":"string"},"attrType":{"type":"string"},"configureVisiable":{"type":"string"},"csrVisiable":{"type":"string"},"defaultValue":{"type":"string"},"extAttrCode":{"type":"string"},"inputType":{"type":"string"},"nullable":{"type":"string"},"offerRelaAttrId":{"type":"integer","format":"int64"},"offerRelaId":{"type":"integer","format":"int64"}},"title":"OfferRelaAttrCO"}},"offerRelaId":{"type":"integer","format":"int64"},"oriOfferCode":{"type":"string"},"oriOfferComments":{"type":"string"},"oriOfferEffDate":{"type":"string","format":"date"},"oriOfferExpDate":{"type":"string","format":"date"},"oriOfferId":{"type":"integer","format":"int64"},"oriOfferName":{"type":"string"},"oriOfferState":{"type":"string"},"oriRentListPrice":{"type":"integer","format":"int64"},"oriSaleListPrice":{"type":"integer","format":"int64"},"relaType":{"type":"string"},"relaTypeName":{"type":"string"}},"title":"OfferRelaDetailCO"}},"offerRuleList":{"type":"array","items":{"type":"object","properties":{"beanName":{"type":"string"},"offerAction":{"type":"string"},"offerId":{"type":"integer","format":"int64"},"offerRuleId":{"type":"integer","format":"int64"},"offerRuleParam":{"type":"array","items":{"type":"object"}},"offerType":{"type":"string"},"ruleCode":{"type":"string"},"ruleId":{"type":"integer","format":"int64"},"ruleImpl":{"type":"string"},"ruleSource":{"type":"string"},"ruleType":{"type":"string"}},"title":"OfferRuleDetailCO"}},"offerType":{"type":"string"},"offerVerId":{"type":"integer","format":"int64"},"paidFlag":{"type":"string"},"priority":{"type":"integer","format":"int64"},"rentListPrice":{"type":"integer","format":"int64"},"saleFlag":{"type":"string"},"saleListPrice":{"type":"integer","format":"int64"},"salesAreaList":{"type":"array","items":{"type":"integer","format":"int64"}},"salesCatgList":{"type":"array","items":{"type":"object","properties":{"catgId":{"type":"integer","format":"int64"},"catgType":{"type":"string"},"limitMessage":{"type":"string"},"limitType":{"type":"string"},"offerId":{"type":"integer","format":"int64"}},"title":"OfferSalesCategoryDetailCO"}},"salesChannelList":{"type":"array","items":{"type":"integer","format":"int64"}},"salesOrgList":{"type":"array","items":{"type":"integer","format":"int64"}},"state":{"type":"string"}},"title":"MainOfferDetailCO"},"errCode":{"type":"string"},"errMessage":{"type":"string"},"success":{"type":"boolean"},"traceId":{"type":"string"}},"title":"SingleResponse«MainOfferDetailCO»"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":false}}},"definitions":{"MultiResponse«OfferCatgCO»":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"catgClass":{"type":"string","description":"Catalog Class"},"catgCode":{"type":"string","description":"Catalog code"},"catgId":{"type":"integer","format":"int64","description":"Offer catalog ID"},"catgName":{"type":"string","description":"Offer catalog Name"},"catgType":{"type":"string","description":"Catalog Type"},"comments":{"type":"string","description":"Comments"},"extValues":{"type":"object"}},"title":"OfferCatgCO"}},"empty":{"type":"boolean"},"errCode":{"type":"string"},"errMessage":{"type":"string"},"notEmpty":{"type":"boolean"},"success":{"type":"boolean"},"traceId":{"type":"string"}},"title":"MultiResponse«OfferCatgCO»"},"OfferCatgCO":{"type":"object","properties":{"catgClass":{"type":"string","description":"Catalog Class"},"catgCode":{"type":"string","description":"Catalog code"},"catgId":{"type":"integer","format":"int64","description":"Offer catalog ID"},"catgName":{"type":"string","description":"Offer catalog Name"},"catgType":{"type":"string","description":"Catalog Type"},"comments":{"type":"string","description":"Comments"},"extValues":{"type":"object"}},"title":"OfferCatgCO"},"PageResponse«OfferCO»":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"comments":{"type":"string","description":"Comments"},"extValues":{"type":"object"},"mrc":{"type":"integer","format":"int64","description":"List Monthly Rental Charge"},"offerCode":{"type":"string","description":"Offer Code"},"offerId":{"type":"integer","format":"int64","description":"Offer ID"},"offerName":{"type":"string","description":"Offer Name"},"offerType":{"type":"string","description":"7: Main Offer"},"offerTypeName":{"type":"string","description":"Main Offer"},"otc":{"type":"integer","format":"int64","description":"List One-time Charge"},"offerAttrList":{"type":"array","items":{"type":"object","properties":{"attrDetail":{"type":"object","properties":{"attrCode":{"type":"string"},"attrId":{"type":"integer","format":"int64"},"attrName":{"type":"string"},"attrType":{"type":"string"},"configureVisiable":{"type":"string"},"csrVisiable":{"type":"string"},"defaultValue":{"type":"string"},"extAttrCode":{"type":"string"},"inputBatch":{"type":"string"},"inputType":{"type":"string"},"nullable":{"type":"string"}},"title":"AttributeDetailCO"},"attrId":{"type":"integer","format":"int64"},"attrValue":{"type":"array","items":{"type":"object","properties":{"attrId":{"type":"integer","format":"int64"},"attrValueId":{"type":"integer","format":"int64"},"parentAttrId":{"type":"integer","format":"int64"},"parentAttrValueId":{"type":"integer","format":"int64"},"value":{"type":"string"},"valueMark":{"type":"string"}},"title":"AttributeValueDetailCO"}},"defaultValue":{"type":"string"},"excludeFlag":{"type":"string"},"mainOfferAttrId":{"type":"integer","format":"int64"},"offerVerId":{"type":"integer","format":"int64"},"prodSpecId":{"type":"integer","format":"int64"}},"title":"MainOfferAttrDetailCO"}}},"title":"OfferCO"}},"empty":{"type":"boolean"},"errCode":{"type":"string"},"errMessage":{"type":"string"},"notEmpty":{"type":"boolean"},"pageIndex":{"type":"integer","format":"int64"},"pageSize":{"type":"integer","format":"int64"},"success":{"type":"boolean"},"totalCount":{"type":"integer","format":"int64"},"totalPages":{"type":"integer","format":"int64"},"traceId":{"type":"string"}},"title":"PageResponse«OfferCO»"},"OfferCO":{"type":"object","properties":{"comments":{"type":"string","description":"Comments"},"extValues":{"type":"object"},"mrc":{"type":"integer","format":"int64","description":"List Monthly Rental Charge"},"offerCode":{"type":"string","description":"Offer Code"},"offerId":{"type":"integer","format":"int64","description":"Offer ID"},"offerName":{"type":"string","description":"Offer Name"},"offerType":{"type":"string","description":"7: Main Offer"},"offerTypeName":{"type":"string","description":"Main Offer"},"otc":{"type":"integer","format":"int64","description":"List One-time Charge"},"offerAttrList":{"type":"array","items":{"type":"object","properties":{"attrDetail":{"type":"object","properties":{"attrCode":{"type":"string"},"attrId":{"type":"integer","format":"int64"},"attrName":{"type":"string"},"attrType":{"type":"string"},"configureVisiable":{"type":"string"},"csrVisiable":{"type":"string"},"defaultValue":{"type":"string"},"extAttrCode":{"type":"string"},"inputBatch":{"type":"string"},"inputType":{"type":"string"},"nullable":{"type":"string"}},"title":"AttributeDetailCO"},"attrId":{"type":"integer","format":"int64"},"attrValue":{"type":"array","items":{"type":"object","properties":{"attrId":{"type":"integer","format":"int64"},"attrValueId":{"type":"integer","format":"int64"},"parentAttrId":{"type":"integer","format":"int64"},"parentAttrValueId":{"type":"integer","format":"int64"},"value":{"type":"string"},"valueMark":{"type":"string"}},"title":"AttributeValueDetailCO"}},"defaultValue":{"type":"string"},"excludeFlag":{"type":"string"},"mainOfferAttrId":{"type":"integer","format":"int64"},"offerVerId":{"type":"integer","format":"int64"},"prodSpecId":{"type":"integer","format":"int64"}},"title":"MainOfferAttrDetailCO"}}},"title":"OfferCO"},"SingleResponse«MainOfferDetailCO»":{"type":"object","properties":{"data":{"type":"object","properties":{"comments":{"type":"string"},"diyMethod":{"type":"string"},"effDate":{"type":"string","format":"date"},"expDate":{"type":"string","format":"date"},"grade":{"type":"integer","format":"int64"},"isBundleFlag":{"type":"string"},"mainProductId":{"type":"integer","format":"int64"},"offerAttrList":{"type":"array","items":{"type":"object","properties":{"attrDetail":{"type":"object","properties":{"attrCode":{"type":"string"},"attrId":{"type":"integer","format":"int64"},"attrName":{"type":"string"},"attrType":{"type":"string"},"configureVisiable":{"type":"string"},"csrVisiable":{"type":"string"},"defaultValue":{"type":"string"},"extAttrCode":{"type":"string"},"inputBatch":{"type":"string"},"inputType":{"type":"string"},"nullable":{"type":"string"}},"title":"AttributeDetailCO"},"attrId":{"type":"integer","format":"int64"},"attrValue":{"type":"array","items":{"type":"object","properties":{"attrId":{"type":"integer","format":"int64"},"attrValueId":{"type":"integer","format":"int64"},"parentAttrId":{"type":"integer","format":"int64"},"parentAttrValueId":{"type":"integer","format":"int64"},"value":{"type":"string"},"valueMark":{"type":"string"}},"title":"AttributeValueDetailCO"}},"defaultValue":{"type":"string"},"excludeFlag":{"type":"string"},"mainOfferAttrId":{"type":"integer","format":"int64"},"offerVerId":{"type":"integer","format":"int64"},"prodSpecId":{"type":"integer","format":"int64"}},"title":"MainOfferAttrDetailCO"}},"offerCode":{"type":"string"},"offerGroupList":{"type":"array","items":{"type":"object","properties":{"necessary":{"type":"string"},"offerGroup":{"type":"object","properties":{"comments":{"type":"string"},"effDate":{"type":"string","format":"date"},"expDate":{"type":"string","format":"date"},"groupType":{"type":"string"},"lowerLimit":{"type":"integer","format":"int64"},"offerGroupCode":{"type":"string"},"offerGroupId":{"type":"integer","format":"int64"},"offerGroupName":{"type":"string"},"offerGroupType":{"type":"string"},"shareFlag":{"type":"string"},"stateDate":{"type":"string","format":"date"},"upperLimit":{"type":"integer","format":"int64"}},"title":"OfferGroupDetailCO"},"offerGroupMemList":{"type":"array","items":{"type":"object","properties":{"defaultFlag":{"type":"string"},"hideFlag":{"type":"string"},"memOfferCode":{"type":"string"},"memOfferComments":{"type":"string"},"memOfferId":{"type":"integer","format":"int64"},"memOfferName":{"type":"string"},"memOfferType":{"type":"string"},"memRentListPrice":{"type":"integer","format":"int64"},"memSaleListPrice":{"type":"integer","format":"int64"},"offerGroupCode":{"type":"string"},"offerGroupId":{"type":"integer","format":"int64"},"offerGroupMemId":{"type":"integer","format":"int64"},"offerGroupName":{"type":"string"},"rstrType":{"type":"string"},"seq":{"type":"integer","format":"int64"},"timeUnit":{"type":"string"}},"title":"OfferGroupMemDetailCO"}},"seq":{"type":"integer","format":"int64"}},"title":"MainOfferGroupDetailCO"}},"offerId":{"type":"integer","format":"int64"},"offerName":{"type":"string"},"offerRelaList":{"type":"array","items":{"type":"object","properties":{"destOfferCode":{"type":"string"},"destOfferComments":{"type":"string"},"destOfferEffDate":{"type":"string","format":"date"},"destOfferExpDate":{"type":"string","format":"date"},"destOfferId":{"type":"integer","format":"int64"},"destOfferName":{"type":"string"},"destOfferState":{"type":"string"},"destRentListPrice":{"type":"integer","format":"int64"},"destSaleListPrice":{"type":"integer","format":"int64"},"offerRelaAttr":{"type":"array","items":{"type":"object","properties":{"attrCode":{"type":"string"},"attrId":{"type":"integer","format":"int64"},"attrName":{"type":"string"},"attrType":{"type":"string"},"configureVisiable":{"type":"string"},"csrVisiable":{"type":"string"},"defaultValue":{"type":"string"},"extAttrCode":{"type":"string"},"inputType":{"type":"string"},"nullable":{"type":"string"},"offerRelaAttrId":{"type":"integer","format":"int64"},"offerRelaId":{"type":"integer","format":"int64"}},"title":"OfferRelaAttrCO"}},"offerRelaId":{"type":"integer","format":"int64"},"oriOfferCode":{"type":"string"},"oriOfferComments":{"type":"string"},"oriOfferEffDate":{"type":"string","format":"date"},"oriOfferExpDate":{"type":"string","format":"date"},"oriOfferId":{"type":"integer","format":"int64"},"oriOfferName":{"type":"string"},"oriOfferState":{"type":"string"},"oriRentListPrice":{"type":"integer","format":"int64"},"oriSaleListPrice":{"type":"integer","format":"int64"},"relaType":{"type":"string"},"relaTypeName":{"type":"string"}},"title":"OfferRelaDetailCO"}},"offerRuleList":{"type":"array","items":{"type":"object","properties":{"beanName":{"type":"string"},"offerAction":{"type":"string"},"offerId":{"type":"integer","format":"int64"},"offerRuleId":{"type":"integer","format":"int64"},"offerRuleParam":{"type":"array","items":{"type":"object"}},"offerType":{"type":"string"},"ruleCode":{"type":"string"},"ruleId":{"type":"integer","format":"int64"},"ruleImpl":{"type":"string"},"ruleSource":{"type":"string"},"ruleType":{"type":"string"}},"title":"OfferRuleDetailCO"}},"offerType":{"type":"string"},"offerVerId":{"type":"integer","format":"int64"},"paidFlag":{"type":"string"},"priority":{"type":"integer","format":"int64"},"rentListPrice":{"type":"integer","format":"int64"},"saleFlag":{"type":"string"},"saleListPrice":{"type":"integer","format":"int64"},"salesAreaList":{"type":"array","items":{"type":"integer","format":"int64"}},"salesCatgList":{"type":"array","items":{"type":"object","properties":{"catgId":{"type":"integer","format":"int64"},"catgType":{"type":"string"},"limitMessage":{"type":"string"},"limitType":{"type":"string"},"offerId":{"type":"integer","format":"int64"}},"title":"OfferSalesCategoryDetailCO"}},"salesChannelList":{"type":"array","items":{"type":"integer","format":"int64"}},"salesOrgList":{"type":"array","items":{"type":"integer","format":"int64"}},"state":{"type":"string"}},"title":"MainOfferDetailCO"},"errCode":{"type":"string"},"errMessage":{"type":"string"},"success":{"type":"boolean"},"traceId":{"type":"string"}},"title":"SingleResponse«MainOfferDetailCO»"},"MainOfferDetailCO":{"type":"object","properties":{"comments":{"type":"string"},"diyMethod":{"type":"string"},"effDate":{"type":"string","format":"date"},"expDate":{"type":"string","format":"date"},"grade":{"type":"integer","format":"int64"},"isBundleFlag":{"type":"string"},"mainProductId":{"type":"integer","format":"int64"},"offerAttrList":{"type":"array","items":{"type":"object","properties":{"attrDetail":{"type":"object","properties":{"attrCode":{"type":"string"},"attrId":{"type":"integer","format":"int64"},"attrName":{"type":"string"},"attrType":{"type":"string"},"configureVisiable":{"type":"string"},"csrVisiable":{"type":"string"},"defaultValue":{"type":"string"},"extAttrCode":{"type":"string"},"inputBatch":{"type":"string"},"inputType":{"type":"string"},"nullable":{"type":"string"}},"title":"AttributeDetailCO"},"attrId":{"type":"integer","format":"int64"},"attrValue":{"type":"array","items":{"type":"object","properties":{"attrId":{"type":"integer","format":"int64"},"attrValueId":{"type":"integer","format":"int64"},"parentAttrId":{"type":"integer","format":"int64"},"parentAttrValueId":{"type":"integer","format":"int64"},"value":{"type":"string"},"valueMark":{"type":"string"}},"title":"AttributeValueDetailCO"}},"defaultValue":{"type":"string"},"excludeFlag":{"type":"string"},"mainOfferAttrId":{"type":"integer","format":"int64"},"offerVerId":{"type":"integer","format":"int64"},"prodSpecId":{"type":"integer","format":"int64"}},"title":"MainOfferAttrDetailCO"}},"offerCode":{"type":"string"},"offerGroupList":{"type":"array","items":{"type":"object","properties":{"necessary":{"type":"string"},"offerGroup":{"type":"object","properties":{"comments":{"type":"string"},"effDate":{"type":"string","format":"date"},"expDate":{"type":"string","format":"date"},"groupType":{"type":"string"},"lowerLimit":{"type":"integer","format":"int64"},"offerGroupCode":{"type":"string"},"offerGroupId":{"type":"integer","format":"int64"},"offerGroupName":{"type":"string"},"offerGroupType":{"type":"string"},"shareFlag":{"type":"string"},"stateDate":{"type":"string","format":"date"},"upperLimit":{"type":"integer","format":"int64"}},"title":"OfferGroupDetailCO"},"offerGroupMemList":{"type":"array","items":{"type":"object","properties":{"defaultFlag":{"type":"string"},"hideFlag":{"type":"string"},"memOfferCode":{"type":"string"},"memOfferComments":{"type":"string"},"memOfferId":{"type":"integer","format":"int64"},"memOfferName":{"type":"string"},"memOfferType":{"type":"string"},"memRentListPrice":{"type":"integer","format":"int64"},"memSaleListPrice":{"type":"integer","format":"int64"},"offerGroupCode":{"type":"string"},"offerGroupId":{"type":"integer","format":"int64"},"offerGroupMemId":{"type":"integer","format":"int64"},"offerGroupName":{"type":"string"},"rstrType":{"type":"string"},"seq":{"type":"integer","format":"int64"},"timeUnit":{"type":"string"}},"title":"OfferGroupMemDetailCO"}},"seq":{"type":"integer","format":"int64"}},"title":"MainOfferGroupDetailCO"}},"offerId":{"type":"integer","format":"int64"},"offerName":{"type":"string"},"offerRelaList":{"type":"array","items":{"type":"object","properties":{"destOfferCode":{"type":"string"},"destOfferComments":{"type":"string"},"destOfferEffDate":{"type":"string","format":"date"},"destOfferExpDate":{"type":"string","format":"date"},"destOfferId":{"type":"integer","format":"int64"},"destOfferName":{"type":"string"},"destOfferState":{"type":"string"},"destRentListPrice":{"type":"integer","format":"int64"},"destSaleListPrice":{"type":"integer","format":"int64"},"offerRelaAttr":{"type":"array","items":{"type":"object","properties":{"attrCode":{"type":"string"},"attrId":{"type":"integer","format":"int64"},"attrName":{"type":"string"},"attrType":{"type":"string"},"configureVisiable":{"type":"string"},"csrVisiable":{"type":"string"},"defaultValue":{"type":"string"},"extAttrCode":{"type":"string"},"inputType":{"type":"string"},"nullable":{"type":"string"},"offerRelaAttrId":{"type":"integer","format":"int64"},"offerRelaId":{"type":"integer","format":"int64"}},"title":"OfferRelaAttrCO"}},"offerRelaId":{"type":"integer","format":"int64"},"oriOfferCode":{"type":"string"},"oriOfferComments":{"type":"string"},"oriOfferEffDate":{"type":"string","format":"date"},"oriOfferExpDate":{"type":"string","format":"date"},"oriOfferId":{"type":"integer","format":"int64"},"oriOfferName":{"type":"string"},"oriOfferState":{"type":"string"},"oriRentListPrice":{"type":"integer","format":"int64"},"oriSaleListPrice":{"type":"integer","format":"int64"},"relaType":{"type":"string"},"relaTypeName":{"type":"string"}},"title":"OfferRelaDetailCO"}},"offerRuleList":{"type":"array","items":{"type":"object","properties":{"beanName":{"type":"string"},"offerAction":{"type":"string"},"offerId":{"type":"integer","format":"int64"},"offerRuleId":{"type":"integer","format":"int64"},"offerRuleParam":{"type":"array","items":{"type":"object"}},"offerType":{"type":"string"},"ruleCode":{"type":"string"},"ruleId":{"type":"integer","format":"int64"},"ruleImpl":{"type":"string"},"ruleSource":{"type":"string"},"ruleType":{"type":"string"}},"title":"OfferRuleDetailCO"}},"offerType":{"type":"string"},"offerVerId":{"type":"integer","format":"int64"},"paidFlag":{"type":"string"},"priority":{"type":"integer","format":"int64"},"rentListPrice":{"type":"integer","format":"int64"},"saleFlag":{"type":"string"},"saleListPrice":{"type":"integer","format":"int64"},"salesAreaList":{"type":"array","items":{"type":"integer","format":"int64"}},"salesCatgList":{"type":"array","items":{"type":"object","properties":{"catgId":{"type":"integer","format":"int64"},"catgType":{"type":"string"},"limitMessage":{"type":"string"},"limitType":{"type":"string"},"offerId":{"type":"integer","format":"int64"}},"title":"OfferSalesCategoryDetailCO"}},"salesChannelList":{"type":"array","items":{"type":"integer","format":"int64"}},"salesOrgList":{"type":"array","items":{"type":"integer","format":"int64"}},"state":{"type":"string"}},"title":"MainOfferDetailCO"},"MainOfferAttrDetailCO":{"type":"object","properties":{"attrDetail":{"type":"object","properties":{"attrCode":{"type":"string"},"attrId":{"type":"integer","format":"int64"},"attrName":{"type":"string"},"attrType":{"type":"string"},"configureVisiable":{"type":"string"},"csrVisiable":{"type":"string"},"defaultValue":{"type":"string"},"extAttrCode":{"type":"string"},"inputBatch":{"type":"string"},"inputType":{"type":"string"},"nullable":{"type":"string"}},"title":"AttributeDetailCO"},"attrId":{"type":"integer","format":"int64"},"attrValue":{"type":"array","items":{"type":"object","properties":{"attrId":{"type":"integer","format":"int64"},"attrValueId":{"type":"integer","format":"int64"},"parentAttrId":{"type":"integer","format":"int64"},"parentAttrValueId":{"type":"integer","format":"int64"},"value":{"type":"string"},"valueMark":{"type":"string"}},"title":"AttributeValueDetailCO"}},"defaultValue":{"type":"string"},"excludeFlag":{"type":"string"},"mainOfferAttrId":{"type":"integer","format":"int64"},"offerVerId":{"type":"integer","format":"int64"},"prodSpecId":{"type":"integer","format":"int64"}},"title":"MainOfferAttrDetailCO"},"AttributeDetailCO":{"type":"object","properties":{"attrCode":{"type":"string"},"attrId":{"type":"integer","format":"int64"},"attrName":{"type":"string"},"attrType":{"type":"string"},"configureVisiable":{"type":"string"},"csrVisiable":{"type":"string"},"defaultValue":{"type":"string"},"extAttrCode":{"type":"string"},"inputBatch":{"type":"string"},"inputType":{"type":"string"},"nullable":{"type":"string"}},"title":"AttributeDetailCO"},"AttributeValueDetailCO":{"type":"object","properties":{"attrId":{"type":"integer","format":"int64"},"attrValueId":{"type":"integer","format":"int64"},"parentAttrId":{"type":"integer","format":"int64"},"parentAttrValueId":{"type":"integer","format":"int64"},"value":{"type":"string"},"valueMark":{"type":"string"}},"title":"AttributeValueDetailCO"},"MainOfferGroupDetailCO":{"type":"object","properties":{"necessary":{"type":"string"},"offerGroup":{"type":"object","properties":{"comments":{"type":"string"},"effDate":{"type":"string","format":"date"},"expDate":{"type":"string","format":"date"},"groupType":{"type":"string"},"lowerLimit":{"type":"integer","format":"int64"},"offerGroupCode":{"type":"string"},"offerGroupId":{"type":"integer","format":"int64"},"offerGroupName":{"type":"string"},"offerGroupType":{"type":"string"},"shareFlag":{"type":"string"},"stateDate":{"type":"string","format":"date"},"upperLimit":{"type":"integer","format":"int64"}},"title":"OfferGroupDetailCO"},"offerGroupMemList":{"type":"array","items":{"type":"object","properties":{"defaultFlag":{"type":"string"},"hideFlag":{"type":"string"},"memOfferCode":{"type":"string"},"memOfferComments":{"type":"string"},"memOfferId":{"type":"integer","format":"int64"},"memOfferName":{"type":"string"},"memOfferType":{"type":"string"},"memRentListPrice":{"type":"integer","format":"int64"},"memSaleListPrice":{"type":"integer","format":"int64"},"offerGroupCode":{"type":"string"},"offerGroupId":{"type":"integer","format":"int64"},"offerGroupMemId":{"type":"integer","format":"int64"},"offerGroupName":{"type":"string"},"rstrType":{"type":"string"},"seq":{"type":"integer","format":"int64"},"timeUnit":{"type":"string"}},"title":"OfferGroupMemDetailCO"}},"seq":{"type":"integer","format":"int64"}},"title":"MainOfferGroupDetailCO"},"OfferGroupDetailCO":{"type":"object","properties":{"comments":{"type":"string"},"effDate":{"type":"string","format":"date"},"expDate":{"type":"string","format":"date"},"groupType":{"type":"string"},"lowerLimit":{"type":"integer","format":"int64"},"offerGroupCode":{"type":"string"},"offerGroupId":{"type":"integer","format":"int64"},"offerGroupName":{"type":"string"},"offerGroupType":{"type":"string"},"shareFlag":{"type":"string"},"stateDate":{"type":"string","format":"date"},"upperLimit":{"type":"integer","format":"int64"}},"title":"OfferGroupDetailCO"},"OfferGroupMemDetailCO":{"type":"object","properties":{"defaultFlag":{"type":"string"},"hideFlag":{"type":"string"},"memOfferCode":{"type":"string"},"memOfferComments":{"type":"string"},"memOfferId":{"type":"integer","format":"int64"},"memOfferName":{"type":"string"},"memOfferType":{"type":"string"},"memRentListPrice":{"type":"integer","format":"int64"},"memSaleListPrice":{"type":"integer","format":"int64"},"offerGroupCode":{"type":"string"},"offerGroupId":{"type":"integer","format":"int64"},"offerGroupMemId":{"type":"integer","format":"int64"},"offerGroupName":{"type":"string"},"rstrType":{"type":"string"},"seq":{"type":"integer","format":"int64"},"timeUnit":{"type":"string"}},"title":"OfferGroupMemDetailCO"},"OfferRelaDetailCO":{"type":"object","properties":{"destOfferCode":{"type":"string"},"destOfferComments":{"type":"string"},"destOfferEffDate":{"type":"string","format":"date"},"destOfferExpDate":{"type":"string","format":"date"},"destOfferId":{"type":"integer","format":"int64"},"destOfferName":{"type":"string"},"destOfferState":{"type":"string"},"destRentListPrice":{"type":"integer","format":"int64"},"destSaleListPrice":{"type":"integer","format":"int64"},"offerRelaAttr":{"type":"array","items":{"type":"object","properties":{"attrCode":{"type":"string"},"attrId":{"type":"integer","format":"int64"},"attrName":{"type":"string"},"attrType":{"type":"string"},"configureVisiable":{"type":"string"},"csrVisiable":{"type":"string"},"defaultValue":{"type":"string"},"extAttrCode":{"type":"string"},"inputType":{"type":"string"},"nullable":{"type":"string"},"offerRelaAttrId":{"type":"integer","format":"int64"},"offerRelaId":{"type":"integer","format":"int64"}},"title":"OfferRelaAttrCO"}},"offerRelaId":{"type":"integer","format":"int64"},"oriOfferCode":{"type":"string"},"oriOfferComments":{"type":"string"},"oriOfferEffDate":{"type":"string","format":"date"},"oriOfferExpDate":{"type":"string","format":"date"},"oriOfferId":{"type":"integer","format":"int64"},"oriOfferName":{"type":"string"},"oriOfferState":{"type":"string"},"oriRentListPrice":{"type":"integer","format":"int64"},"oriSaleListPrice":{"type":"integer","format":"int64"},"relaType":{"type":"string"},"relaTypeName":{"type":"string"}},"title":"OfferRelaDetailCO"},"OfferRelaAttrCO":{"type":"object","properties":{"attrCode":{"type":"string"},"attrId":{"type":"integer","format":"int64"},"attrName":{"type":"string"},"attrType":{"type":"string"},"configureVisiable":{"type":"string"},"csrVisiable":{"type":"string"},"defaultValue":{"type":"string"},"extAttrCode":{"type":"string"},"inputType":{"type":"string"},"nullable":{"type":"string"},"offerRelaAttrId":{"type":"integer","format":"int64"},"offerRelaId":{"type":"integer","format":"int64"}},"title":"OfferRelaAttrCO"},"OfferRuleDetailCO":{"type":"object","properties":{"beanName":{"type":"string"},"offerAction":{"type":"string"},"offerId":{"type":"integer","format":"int64"},"offerRuleId":{"type":"integer","format":"int64"},"offerRuleParam":{"type":"array","items":{"type":"object"}},"offerType":{"type":"string"},"ruleCode":{"type":"string"},"ruleId":{"type":"integer","format":"int64"},"ruleImpl":{"type":"string"},"ruleSource":{"type":"string"},"ruleType":{"type":"string"}},"title":"OfferRuleDetailCO"},"OfferSalesCategoryDetailCO":{"type":"object","properties":{"catgId":{"type":"integer","format":"int64"},"catgType":{"type":"string"},"limitMessage":{"type":"string"},"limitType":{"type":"string"},"offerId":{"type":"integer","format":"int64"}},"title":"OfferSalesCategoryDetailCO"}}}]`;

const capabilityOpenPlatformBasePath = '/zmp-pr/db-zmpapi';

const domXmlContent = `[]`;

const client = new GraphQLClient('/5gvtest/api/graphql', {
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    [headerName]: jwtToken,
  },
});

const request = async (url: string, data: any = {}) => {
  data.headers = data.headers ? {...data.headers, [headerName]: jwtToken} : {[headerName]: jwtToken};
  const res = await fetch(url, data);
  return res;
}

const copyToClipboard = (value: string) => {
  copy(value);
}

export const Pinyin = (value: string) => {
  const { pinyin } = pinyinPro;
  return pinyin(value, { toneType: 'none', type: 'array' }).join('')
}

const transRemoteOptions = (data: any[]) => {
  return data.map(v => {
    const values = Object.values(v);
    return {
      label: values[1],
      value: values[0],
    }
  })
}

function loadFileDoc(filePath: string) {
  let xmlDoc;
  try {
    //Internet Explorer
    xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
    xmlDoc.async = false;
    xmlDoc.load(filePath);
  } catch (e) {
    try {
      //Firefox, Mozilla, Opera, etc.
      xmlDoc = document.implementation.createDocument('', '', null);
      xmlDoc.async = false;
      xmlDoc.load(filePath);
    } catch (e) {
      try {
        //Google Chrome
        const xmlhttp = new window.XMLHttpRequest();
        xmlhttp.open('GET', filePath, false);
        xmlhttp.send(null);
        return xmlhttp.responseText;
      } catch (e) {
        console.error(e.message);
      }
    }
  }
  return xmlDoc.outerHTML;
}

/**
 * 根据XML获取Json
 * @param formXml 
 * @param xmlPata 
 */
 export const getJsonByXml = (xml_str: any) => {
  const entities = xml_str(`Object`).toArray().map((v) => {
    const $entity = xml_str(v);
    const entity = { ...$entity.attr() };
    const fields = $entity.children('Field').toArray().map((ele) => {
      const filed = xml_str(ele).attr();
      const $options = xml_str(ele).children('Options').toArray();
      if ( $options.length > 0 ) {
        const options = xml_str(ele).children('Options').toArray().map((opts) => {
          const refId = xml_str(opts).attr("ref-id")
          const option = xml_str(`Collection`).children(`Options[id=${refId}]`).children('Option').toArray().map((opt) => xml_str(opt).attr());
          return option;
        });
        filed.options = options[0];
      }
      return filed;
    });
    entity.fields = fields;
    return entity;
  });
  return entities;
}

function createRestDefaultFunction(param: any) {
  const { title = '', modelType = '', description = '', isPublic = 'false', exposeReadOnly = 'true', ...restChild } = param;
  // 新建的时候, 查找主键的id的title,name,type
  const { children = [] } = restChild || {};
  const findPrimaryNode = children.filter((v) => v.primaryKey);
  const primaryKeyNodeTitle = findPrimaryNode[0].title;
  const primaryKeyNodeName = findPrimaryNode[0].name;
  const primaryKeyNodeType = findPrimaryNode[0].type;
  let modelName = param.name;
  modelName = modelName.substring(0, 1).toUpperCase() + modelName.substring(1);
  const createChildren = (flag) => {
    const getChild = param.children || param.fields || [];
    let childs = getChild.map((vl) => ({
      ...vl,
      key: `${flag}${vl.key}`
    }));
    childs = [...childs.filter((vl) => vl.iconType !== 'function')]
    return [
      {
        title: modelName,
        iconType: 'entity',
        key: `${flag}${modelName}`,
        name: param.name,
        type: modelName,
        required: 'false',
        children: childs,
      }
    ]
  };
  const createFunctionBasic = (flag) => ({
    title: flag,
    name: flag,
    key: flag,
    id: uuid(),
    iconType: 'function',
  });
  const createIDBasic = (flag) => ({
    title: primaryKeyNodeTitle || 'id',
    name: primaryKeyNodeName || 'id',
    type: primaryKeyNodeType || 'integer',
    id: uuid(),
    key: `${flag}id`,
  });
  const createIDInput = (flag) => ({
    ...createIDBasic(flag),
    iconType: 'input',
    required: 'true',
  });
  const createFilter = (flag) => ([
    { title: '_where', name: '_where', key: `${flag}-where`, iconType: 'input', id: uuid() },
    { title: '_limit', name: '_limit', key: `${flag}-limit`, iconType: 'input', id: uuid(), type: 'Integer' },
    { title: '_offset', name: '_offset', key: `${flag}-offset`, iconType: 'input', id: uuid(), type: 'Integer' },
    { title: '_order_by', name: '_order_by', key: `${flag}-order-by`, iconType: 'input', id: uuid() },
    { title: '_group_by', name: '_group_by', key: `${flag}-group-by`, iconType: 'input', id: uuid() },
  ]);
  const createIDOutput = (flag) => ({
    ...createIDBasic(flag),
    iconType: 'output',
  });
  const createParamBasic = (flag) => ({
    key: flag,
    children: createChildren(flag),
  });
  const createParamInput = (flag, param) => ({
    ...createParamBasic(flag),
    title: param || 'Source',
    name: param || 'Source',
    type: `${modelName}`,
    iconType: 'input',
    innerType: 'class',
    required: 'true',
  });
  const createParamOutput = (flag, param = '') => ({
    ...createParamBasic(flag),
    title: 'Record',
    name: 'Record',
    type: param || `${modelName} List`,
    innerType: 'class',
    iconType: 'output',
  });
  const restDefaultFunction = [
    {
      ...createFunctionBasic(`Create${modelName}`),
      functionType: 'Create Entity',
      description: 'Adds a new entity record to the database.',
      isFunction: 'false',
      children: [
        createParamInput(`Create${modelName}Source`, 'toCreate'),
        createIDOutput(`Create${modelName}id`)
      ]
    }, {
      ...createFunctionBasic(`CreateOrUpdate${modelName}`),
      functionType: 'Create Or Update Entity',
      description: 'Adds a new entity record to the database. If the record already exists, all attributes will be replaced with the new ones.',
      isFunction: 'false',
      children: [
        createParamInput(`CreateOrUpdate${modelName}Source`, 'toCreate'),
        createIDOutput(`CreateOrUpdate${modelName}id`)
      ]
    }, {
      ...createFunctionBasic(`Update${modelName}`),
      functionType: 'Update Entity',
      description: 'Replaces all attributes in an entity record in the database.',
      isFunction: 'false',
      children: [
        createParamInput(`Update${modelName}Source`, 'toUpdate'),
        createIDOutput(`Update${modelName}id`),
      ]
    }, {
      ...createFunctionBasic(`Get${modelName}`),
      functionType: 'Get Entity',
      description: 'Reads an existing entity record from the database through its identifier.',
      isFunction: 'false',
      children: [
        createIDInput(`Get${modelName}id`),
        createParamOutput(`Get${modelName}Record`, modelName),
      ]
    }, {
      ...createFunctionBasic(`Get${modelName}ByFilter`),
      functionType: 'Get Entity By Filter',
      description: 'Reads an entity record from the database through its identifier and prevents other requests from accessing it until its updated.',
      isFunction: 'false',
      children: [
        ...createFilter(`Get${modelName}Filter`),
        createParamOutput(`Get${modelName}RecordByFilter`),
      ]
    }, {
      ...createFunctionBasic(`Delete${modelName}`),
      functionType: 'Delete Entity',
      description: 'Removes an entity record from the database.',
      isFunction: 'false',
      children: [
        createIDInput(`Delete${modelName}`),
        createIDOutput(`Delete${modelName}Out`),
      ]
    }
  ]
  return restDefaultFunction;
}

function getEntryData(AllEntities: any[]) {
  let copyRestData: any[] = [];
  let copyEntitiesData: any[] = [];
  const databaseData: any[] = [];
  if (Array.isArray(AllEntities) && AllEntities.length > 0) {
    const newData = cloneDeep(AllEntities);
    newData.map((item) => {
      let getItem = cloneDeep(item);
      getItem.fields = getItem.fields.map((vl) => {
        return {
          ...vl,
          title: vl.name,
          key: `${item.name}-${vl.name}`,
          entityId: item.id,
          required: !item.nullable,
          code: vl.code ? vl.code : `${getItem.name}_${vl.name}`,
          type: vl.name === 'id' ? 'Long' : (vl.type || 'text'),
        }
      });
      const getItemUpperCase = getItem.name.substring(0, 1).toUpperCase() + getItem.name.substring(1);
      getItem = {
        ...getItem,
        title: getItemUpperCase,
        iconType: 'entity',
        modelType: 'entity',
        key: getItem.name,
        type: getItem.name,
        isPublic: 'false',
        exposeReadOnly: 'true',
        code: getItem.code ? getItem.code : `ly_${getItem.name}`,
      }
      getItem.children = getItem.fields;
      const restDefaultFunction = createRestDefaultFunction(getItem);
      const cloneItem = cloneDeep(getItem);
      const { fields } = cloneItem;
      cloneItem.children = [...fields.filter((t) => t.iconType !== 'function'), ...restDefaultFunction];
      databaseData.push(cloneItem);
    });
    // entitiesData[1].children[0].children = databaseData;
    databaseData.map((vl) => {
      const copyFunDefaultValue = cloneDeep(vl);
      const copyDataDefaultValue = cloneDeep(vl);
      delete copyFunDefaultValue.fields;
      delete copyDataDefaultValue.fields;
      copyFunDefaultValue.children = copyFunDefaultValue.children.filter((a) => a.iconType === 'function');
      copyDataDefaultValue.children = copyDataDefaultValue.children.filter((a) => a.iconType !== 'function');
      if (!copyRestData.find((v) => v.name === copyFunDefaultValue.name)) {
        copyRestData.push(copyFunDefaultValue);
      }
      if (!copyEntitiesData.find((v) => v.name === copyDataDefaultValue.name)) {
        copyEntitiesData.push(copyDataDefaultValue);
      }
    });
  }
  return copyEntitiesData;
}

function transformComponentByType(flag: string) {
  switch (flag) {
    case 'Integer':
      return 'inputNumber';
    case 'Long':
      return 'inputNumber';
    case 'Boolean':
      return 'switch';
    case 'String':
      return 'input';
    case 'Time':
      return 'timePicker';
    case 'Data':
      return 'datePicker';
    case 'DateTime':
      return 'datePicker';
    case 'Float':
      return 'inputNumber';
    case 'Double':
      return 'inputNumber';
    case 'Picklist':
      return 'select';
    case 'Picklist(Multi-Select)':
      return 'multiselect';
    case 'Text':
      return 'input';
    case 'TextArea':
      return 'textArea';
    case 'EncryptedText':
      // 密码框
      return 'password';
    case 'LongText':
      return 'textArea';
    case 'RichText':
      // 超文本
      return 'textArea';
    case 'PhoneNumber':
      return 'input';
    case 'Binary':
      // 二进制
      return 'upload';
    case 'Decimal':
        //十进制
      return 'input';
    case 'Currency':
      //货币
      return 'inputNumber';
    case 'Icon':
      return 'input';
    case 'Image':
      return 'input';
    case 'Email':
      return 'input';
    case 'URL':
    default:
      return 'input';
  }
};

function swaggerParser(swaggerData: any) {
  const {
    host,
    paths,
    schemes,
    basePath,
    definitions = {},
    info: { title, description },
  } = swaggerData;

  const services: any[] = [];
  const dtos: any[] = [];
  const restApiData: any = [{ title, key: uuid(), description, basePath, host, schemes, iconType: 'importSwagger', children: services }];
  const entitiesApiData: any = [{ title, key: uuid(), description, basePath, host, schemes, iconType: 'importSwagger', children: dtos }];
  let id = 1;
  let getDataRequired = [];

  function createChildren(data: any, args: any) {
    Object.keys(data).forEach(prop => {
      const propVal = data[prop];
      const { type, properties, items, ...rest } = propVal;
      getDataRequired = [...new Set(getDataRequired)];
      const propObj: any = {
        ...rest,
        type,
        key: `${++id}`,
        title: prop,
        iconType: type === 'object' || type === 'array' ? 'databases' : 'database',
      };
      if (getDataRequired?.length > 0) {
        getDataRequired.map(vl => {
          if (vl === propObj.title) {
            propObj.required = true;
          }
        });
      }
      let propData: any;
      if (type === 'object') {
        propData = properties;
      }
      if (type === 'array') {
        if (items.type === 'object') {
          propData = items.properties;
        } else {
          propObj.items = items;
        }
      }
      if (propData) {
        propObj.children = [];
        Object.keys(propData).forEach(v => {
          propObj.children.push({
            ...propData[v],
            key: `${++id}`,
            title: v,
            iconType: 'database',
          });
        });
      }
      args.children.push(propObj);
    });
  }

  for (const [key, value] of Object.entries(definitions)) {     // eslint-disable-line
    const { properties, required } = value as any;
    const dataProps = {
      dataSource: [],
    };
    const obj: any = {
      key: `${++id}`,
      title: key,
      name: key,
      iconType: 'importAPI',
      children: [],
    };
    const getDatasource = [];
    for (const [prop, propVal] of Object.entries(properties)) {   // eslint-disable-line
      const propObj: any = {
        ...(propVal as any),
        key: `${++id}`,
        title: prop,
        name: prop,
        iconType: 'database',
      };
      if (required?.length > 0) {
        getDataRequired = [...getDataRequired, ...required];
        required.map(v => {
          if (v === prop) {
            propObj.required = true;
          }
        });
      }
      obj.children.push(propObj);
      getDatasource.push({
        type: transformComponentByType(propObj?.type),
        data: {
          formSettings: {
            name: prop,
            label: prop,
            defaultValue: '',
          }
        }
      });
    }
    dataProps.dataSource = getDatasource;
    dtos.push(obj);
  }

  for (const [path, val] of Object.entries(paths)) {              // eslint-disable-line
    for (const [method, res] of Object.entries(val as any)) {     // eslint-disable-line
      const { operationId, parameters = [], responses = {}, consumes = [], produces = [] } = res as any;
      const obj: any = {
        path,
        method,
        key: `${++id}`,
        title: operationId,
        iconType: 'importAPI',
        children: [],
      };
      if (consumes.length > 0) {
        obj.consumes = consumes[0];
      } else if (produces.length > 0) {
        obj.produces = produces[0];
      }

      parameters.forEach((param: any) => {    // eslint-disable-line
        const { name, ...rest } = param;
        const args: any = {
          ...rest,
          key: `${++id}`,
          title: name,
          state: 'input',
          iconType: 'input',
        };
        let data: any;
        if (param.type === 'array' && param.items.type === 'object') {
          args.type = 'array';
          args.children = [];

          data = param.items.properties;
        }
        if (param.schema) {
          args.type = param.schema.type;
          args.children = [];
          if (args.type === 'object') {
            data = param.schema.properties;
          }
          if (args.type === 'array') {
            data = param.schema.items.properties;
          }
        }

        if (data) {
          createChildren(data, args);
        }
        obj.children.push(args);
      });

      Object.keys(responses).forEach(status => {      // eslint-disable-line
        const res = responses[status];
        if (status === '200') {
          const {
            schema: { type = '', properties = null, items = null } = {},
          } = res;
          const resObj: any = {
            type,
            key: `${++id}`,
            title: 'Response',
            state: 'output',
            iconType: 'output',
          };
          let data: any;
          if (properties) {
            resObj.children = [];
            data = properties;
          }
          if (items) {
            if (items.type === 'object') {
              resObj.children = [];
              data = items.properties;
            } else {
              resObj.items = items;
            }
          }
          if (data) {
            createChildren(data, resObj);
          }
          obj.children.push(resObj);
        }
      });
      services.push(obj);
    }
  }
  return { restApiData, entitiesApiData };
}

const runSeverActionCall = async (method: string, params: any) => {
  const obj: any = {};
  const paramMap:any = {}
  serverActionList[method].forEach((p:string, index:number) => {
    paramMap[p] = params[index];
  });
  obj.paramMap = paramMap;
  obj.actionName = method;
  const { RunServerAction } = await client.query(
    gql`
        query RunServerAction($actionName: Text, $paramMap: Object) {
          RunServerAction(actionName: $actionName, paramMap: $paramMap)
        }
      `,
    obj
  );
  return RunServerAction;
}

const call = async (method: string, ...rest) => {
  const apiDocs = JSON.parse(swaggerList);
  for (let j = 0; j < apiDocs.length; j++) {
    const element = apiDocs[j];
    const { restApiData } = swaggerParser(element);
    restData = restData.concat(restApiData);
  }
  let bathPath: string;
  let fetchUrl: any;
  let swaggerObj: any;
  let isSwagger: boolean = false;
  let restParam = cloneDeep(rest);
  if (!serverActionList[method]) {
    restData.forEach(v => {
      bathPath = v.basePath || '';
      v.children.forEach(ele => {
        if (ele.title === method) {
          isSwagger = true;
          fetchUrl = `${bathPath}${ele.path}`;
          swaggerObj = cloneDeep(ele);
        }
      })
    });
    if (isSwagger) {
      let i = 0;
      let res;
      if (fetchUrl.indexOf('{') !== -1) {
        let newUrl = fetchUrl.replace(/\{([\s\S]*?)\}/g, function(match, key) {
          return restParam[i++];
        });
        fetchUrl = newUrl;
      } else {
        let queryStr = '';
        swaggerObj.children.forEach(v => {
          if (v.iconType === "input" && v.in === "query") {
            queryStr += i === 0 ? `${v.title}=${restParam[i++]}` : `&${v.title}=${restParam[i++]}`;
          }
        });
        if (queryStr) {
          fetchUrl = `${fetchUrl}?${queryStr}`;
        }
      }
     if (swaggerObj.method === 'get' && fetchUrl.indexOf(capabilityOpenPlatformBasePath) > -1 ){
          if(fetchUrl.indexOf('?') > -1){
             fetchUrl += `&appCode=5gvtest`;
          }else{
             fetchUrl += `?appCode=5gvtest`;
          }
      }
      const fetchData: any = {method: swaggerObj.method};
      if ((swaggerObj.method === 'post' || swaggerObj.method === 'patch') && restParam[i]) {
        fetchData.data = restParam[i];
        if( fetchData.data && fetchUrl.indexOf(capabilityOpenPlatformBasePath) > -1 ){
          fetchData.data.appCode = `5gvtest`
        }
      }
      res = await request(fetchUrl, fetchData);
      return {Response: res};
    } else {
      if (method === 'GetPickList') {
        let param = {};
        let queryStr = '';
        const declArr: string[] = [];
        rest[0].forEach(v => {
          declArr.push(`$${v.name}_id: Long!`);
          queryStr += `${v.name}:GetPickList(id: $${v.name}_id) {
            picklistValues {
              label
              value
            }
          }\n`;
          param[`${v.name}_id`] = v.id;
        });
        const graphqlStr = `
          query (${declArr.join(', ')}) {
            ${queryStr}
          }
        `;
        const res = await client.query(
          gql`${graphqlStr}`,
          param
        );
        return res;
      } else {
        let entityName = method.replace(/^Delete|^Patch|^Create(OrUpdate)?|^Update|^Get/, '').replace(/ByFilter$/, '').replace(/Collection$/, '');
        let graphqlType = method.replace(entityName, '');
        let param = {};
        let graphqlStr;
        const entitiesData = getEntryData(JSON.parse(domXmlContent));
        const entityData = entitiesData.find(v => v.name === entityName);
        let entityPropStr = '';
        const declArr: string[] = [];
        const parArr: string[] = [];
        if (entityData) {
          entityData.children.forEach((v, i) => {
            if (v.primaryKey === 'true') {
              declArr.push(`$${v.name}: ${v.type}!`);
              parArr.push(`${v.name}: $${v.name}`);
              if (graphqlType === 'Get' || graphqlType === 'Delete') {
                param[v.name] = rest[i];
              }
            }
            entityPropStr += i === entityData.children.length - 1 ? v.name : `${v.name}\n`;
          });
        }
        switch (graphqlType) {
          case 'Get':
            graphqlStr = `
              query (${declArr.join(', ')}) {
                ${method}(${parArr.join(', ')}) {
                  ${entityPropStr}
                }
              }
            `;
            break;
          case 'Delete':
            graphqlStr = `
              mutation (${declArr.join(', ')}) {
                ${method}(${parArr.join(', ')})
              }
            `;
            break;
          // 这块还需要修改下，过滤条件参数还未确定
          case 'GetByFilter':
            graphqlStr = `
              query {
                ${method} {
                  ${entityPropStr}
                }
              }
            `;
            break;
          case 'PatchCollection':
            graphqlStr = `
              mutation ($toUpdate: [${entityName}Input!]) {
                ${method}(toUpdate: $toUpdate)
              }
            `;
            param = {toUpdate: rest[0]};
            break;
          case 'Create':
            graphqlStr = `
              mutation ($toCreate: [${entityName}Input!]) {
                ${method}(toCreate: $toCreate) {
                  ${entityPropStr}
                }
              }
            `;
            param = {toCreate: rest[0]};
            break;
          case 'CreateOrUpdate':
            graphqlStr = `
              mutation ($toCreate: [${entityName}Input!]) {
                ${method}(toCreate: $toCreate) {
                  ${entityPropStr}
                }
              }
            `;
            param = {toCreate: rest[0]};
            break;
          case 'Update':
            graphqlStr = `
              mutation ($toUpdate: ${entityName}Input) {
                ${method}(toUpdate: $toUpdate)
              }
            `;
            param = {toUpdate: rest[0]};
            break;
          default:
            break;
        }
        let res;
        if (Object.keys(param).length) {
          res = await client.query(
            gql`${graphqlStr}`,
            param
          );
        } else {
          res = await client.query(
            gql`${graphqlStr}`
          );
        }
        return res[method];
      }
    }
  } else {
    return runSeverActionCall(method, rest);
  }
}

const get = async (sqlName: string, data: any = {}, QueryMap: any) => {
  let obj: any = {};
  if (data.pageIndex) {
    obj.pageIndex = data.pageIndex;
    delete data.pageIndex;
  }
  if (data.pageSize) {
    obj.pageSize = data.pageSize;
    delete data.pageSize;
  }
  obj.params = JSON.stringify(data);
  obj.qson = `5gvtest/${sqlName}`;
  let { GetBySql } = await client.query(
    gql`
        query ($qson: Text, $params: LongText, $pageIndex: Integer, $pageSize: Integer) {
          GetBySql(qson: $qson, params: $params, pageIndex: $pageIndex, pageSize: $pageSize)
        }
      `,
    obj
  );
  const res = JSON.parse(GetBySql);
  const newRes = new (QueryMap[sqlName])(res.list, res.total);
  return newRes;
}

const getCurrentDate = (date:string, format: string = 'yyyy-mm-dd hh:ii:ss') => {
  return dateUtils.format(date ? new Date(date) : new Date(), format);
}

const transDsPropName = (data: any[], label: string, value: string, entity?: any) => {
  if (data) {
    if (entity) {
      const newData: Array<any> = [];
      data.forEach((v: any) => {
        const obj = v[entity];
        if (!newData.some(item => item.value == obj[value])) {
          newData.push(Object.assign(obj, {label: obj[label], value: obj[value]}));
        }
      });
      return newData;
    } else {
      return data.map(v => Object.assign(v, {label: v[label], value: v[value]}));
    }
  } 
  return [];
};

const GetUrlName = (record) => {
  if (!record) {
    return '';
  }
  const urlArr = record.split('/');
  return urlArr[urlArr.length - 1]
}

const LabelFunction = (record, valueMap) => {
  return valueMap[record];
}

const transformData = data => {
  function modifyData(obj) {
    Object.keys(obj).forEach(key => {
      const value = obj[key];
      if (value === null || value === undefined) {
        delete obj[key];
      } else {
        if (typeof value === 'string' && (value.match(dateReg) || value.match(timeReg))) {
          obj[key] = moment(value);
        }
        if (typeof value === 'object') {
          if (value._isAMomentObject) {
            obj[key] = value.valueOf();
          } else {
            obj[key] = transformData(value);
          }
        }
      }
    });
  }
  if (Object.prototype.toString.call(data) === "[object Array]") {
    data.forEach(v => {
      modifyData(v);
    });
  } else if (Object.prototype.toString.call(data) === "[object Object]") {
    modifyData(data);
  }
  return data;
}

const setStatePromise = (that: any, newState: any, fn: any) => {
  return new Promise((resolve) => {
    that.setState(newState, () => {
      if (fn) {
        fn();
      }
      resolve(null);
    });
  });
}

const getUrlQueryParam = (propName: string) => {
  const currentUrl = window.location.href;
  let res = '';
  if (!currentUrl || !propName) {
    return res;
  }
  const urlArr = currentUrl.split('?');
  const params = urlArr[1];
  if (params) {
    const paramsArr = params.split('&');
    paramsArr.forEach(p => {
      const pName = p.split('=')[0];
      if (pName === propName) res = p.split('=')[1];
    });
  }
  return res;
};

const LocalDataSet = (name: string, value: string) => {
  const valueData = typeof value === 'string' ? value : JSON.stringify(value);
  window.localStorage.setItem(name, valueData);
};

const LocalDataGet = (name: string) => {
  const data: string | null = window.localStorage.getItem(name);
  if (data) {
    try {
      return JSON.parse(data);
    } catch (error) {
      return data;
    }
  }
  return data;
};

const SetUserId = (value: string) => window.localStorage.setItem('userId', value);

const GetUserId = () => window.localStorage.getItem('userId') || '';

const CurrDateTime = () => dateUtils.format(new Date(), 'yyyy-mm-dd hh:ii:ss');

const CurrDate = () => dateUtils.format(new Date(), 'yyyy-mm-dd');

const NullValue = () => null;

const popup = {
  confirm: (title: string, content: string) => {
    return new Promise((resolve, reject) => {
      Modal.confirm({
        title,
        content,
        onOk: () => {
          resolve(true);
        },
        onCancel: () => {
          resolve(false);
        }
      });
    })
  }
}

export {
  get,
  call,
  popup,
  client,
  request,
  GetUrlName,
  getCurrentDate,
  copyToClipboard,
  LabelFunction,
  transformData,
  setStatePromise,
  transDsPropName,
  getUrlQueryParam,
  transRemoteOptions,
  LocalDataSet,
  LocalDataGet,
  GetUserId,
  SetUserId,
  CurrDateTime,
  CurrDate,
  NullValue
};